﻿namespace DomainSerializer.Controllers
{
    using DomainSerializer.Domains;
    using System.Runtime.Serialization;
    using System.Xml;
    using System;
    using System.IO;
    class DomainXMLWriter
    {
        string path = @"..\..\..\..\..\Documents\Domains\Exapmles\";

        /// <summary>
        /// Serializes the specified object, that implements IDomain interface.
        /// </summary>
        /// <param name="serializable">IDomain serializable.</param>
        /// <returns> true if completed, false if object is not IDomain</returns>
        public bool Serialize(object serializable)
        {
            if (serializable is IDomain)
            {
                var ds = new DataContractSerializer(serializable.GetType());
                var settings = new XmlWriterSettings { Indent = true };
                var settingsForReader = new XmlReaderSettings { };

                int filecount = 0;
                while (File.Exists(path + serializable.GetType() + filecount + ".xml"))
                {
                    filecount++;
                }

                using (var w = XmlWriter.Create(path + serializable.GetType() + filecount + ".xml", settings))
                    ds.WriteObject(w, serializable);
                return true;
            }

            return false;
        }

        /// <summary>
        /// Serializes the specified objects array, that implements IDomain interface.
        /// </summary>
        /// <param name="serializable">IDomain serializable.</param>
        /// <returns> true if completed, false if object is not IDomain</returns>
        public bool Serialize(object[] serializable)
        {
            if (serializable[0] is IDomain)
            {
                var ds = new DataContractSerializer(serializable.GetType());
                var settings = new XmlWriterSettings { Indent = true };
                var settingsForReader = new XmlReaderSettings { };

                int filecount = 0;
                while (File.Exists(path + serializable.GetType() + filecount + ".xml"))
                {
                    filecount++;
                }

                using (var w = XmlWriter.Create(path + serializable.GetType() + filecount + ".xml", settings))
                    ds.WriteObject(w, serializable);
                return true;
            }

            return false;
        }
    }
}
